var util = require('../../utils/util.js');
var api = require('../../config/api.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    backType: 'index' //index:返回首页 mine:返回用户中心 other 返回此id的文章明细
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.backType) {
      this.setData({
        backType: options.backType
      });
    }
    // 查看是否授权
    /*wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              app.globalData.userInfo = res.userInfo
            }
          })
        }
      }
    })*/
  },

  bindGetUserInfo: function() {
    let backtype = this.data.backType;
    let code = null;
    this.toLogin().then(res => {
      code = res.code;
    }).then(res => {
      return this.getUserInfo();
    }).then(userInfo => {
      console.log(userInfo)
      util.request(api.login, {
        code: code,
        fullUserInfo: JSON.stringify(userInfo)
      }, 'POST').then(res => {
        wx.setStorageSync('mini-token', res.data.token);
        wx.setStorageSync('userInfo', res.data.userInfo);
        wx.navigateBack({
          delta: 1
        })
      });
    });
  },

  //返回首页 
  navigateBack: function(e) {
    wx.switchTab({
      url: '../index/index'
    })
  },

  checkUserInfo: function() {
    app.checkUserInfo(function(userInfo, isLogin) {
      if (!isLogin) {
        wx.redirectTo({
          url: '../authorization/authorization'
        })
      } else {
        that.setData({
          userInfo: userInfo
        });
      }
    });
  },

  /**
   * 调用微信登录
   */
  toLogin: function() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: function(res) {
          if (res.code) {
            //登录远程服务器
            resolve(res);
          } else {
            reject(res);
          }
        },
        fail: function(err) {
          reject(err);
        }
      });
    });
  },
  getUserInfo: function() {
    return new Promise(function(resolve, reject) {
      wx.getUserInfo({
        withCredentials: true,
        success: function(res) {
          // console.log(res);
          resolve(res);
          // wx.navigateBack({
          //   delta:1
          // })
        },
        fail: function(err) {
          reject(err);
          util.showErrorModal('很遗憾，您拒绝了微信授权，宝宝很伤心');
        }
      })
    });
  }
});